/*
 * @Author: 肖思汗 
 * @Date: 2025-07-11 10:04:50 
 * @Last Modified by: xiehangyun
 * @Last Modified time: 2025-07-29 16:33:48
 */


import { Close } from '@nutui/icons-react-taro';
import { NavBar } from '@nutui/nutui-react-taro';
import clsx from 'clsx';
import { observer } from "mobx-react-lite";
import { ReactNode, useEffect, useRef, useState } from 'react';
import styles from './myPopup.module.less';
import utilsStore from '../../utils/utilsStore';

interface Iprops {
    children?: ReactNode;
    open?: boolean;
    className?: string;
    closeable?: boolean;
    hasHeader?: boolean;
    title?: string;
    onClose?: () => void;
    leftNode?: ReactNode;
    hasMark?: boolean;
}

// 组件
const MyPopup = observer((props: Iprops) => {

    const dom = useRef<HTMLDivElement | null>(null);
    const [open, setOpen] = useState(props.open);
    const [visible, setVisible] = useState(false);

    useEffect(() => {
        (async () => {
            if (props.open) {
                setOpen(true);
                await new Promise(resolve => requestAnimationFrame(resolve));
                await new Promise(resolve => requestAnimationFrame(resolve));
                setVisible(true);
            } else {
                setVisible(false);
                setTimeout(() => {
                    setOpen(false);
                }, 300);
            }
        })();
    }, [props.open]);

    if (!open) {
        return null;
    }

    return (
        <div className={clsx(styles.myPopupMask, [undefined, true].includes(props.hasMark) && styles.hasMark)} >
            <div
                className={clsx(styles.myPopup, "myPopup", visible && styles.visible, props.className)}
                style={{
                    paddingTop: "20rpx",
                    paddingBottom: utilsStore.safeAreaBottom > 0 ? utilsStore.safeAreaBottom : "20rpx"
                }}
            >
                {
                    props.hasHeader !== false &&
                    <NavBar
                        className={clsx(styles.header, "header")}
                        left={props.leftNode}
                        right={
                            props.closeable !== false &&
                            <Close onClick={props.onClose} />
                        }
                    >
                        {props.title || "弹出层"}
                    </NavBar>
                }
                {props.children}
            </div>

        </div>
    );
});

export default MyPopup;